import { useUserInfo } from "@/store";
import { getCurrentInstance } from "vue";
import { createRouter, createWebHashHistory, RouteRecordRaw } from "vue-router";

const modules: Record<string, Record<string, any>> = import.meta.glob(
  "./modules/*.ts",
  { eager: true }
);

let routeArray: RouteRecordRaw[] = [];
for (const path in modules) {
  routeArray = [...routeArray, ...modules[path].routes];
}
const routes = [
  {
    path: "/",
    redirect: "/project",
  },
  ...routeArray,
];

const router = createRouter({
  history: createWebHashHistory(),
  routes,
  scrollBehavior(to, from, savedPosition) {
    return new Promise((resolve) => {
      if (savedPosition) {
        resolve(savedPosition);
      } else {
        resolve({ top: 0, left: 0 });
      }
    });
  },
});
router.beforeEach((to, from, next) => {
  try {
    if (to.name === "Login") {
      next();
      return;
    }
    const { $loading } =
      getCurrentInstance()?.appContext?.config.globalProperties || {};
    $loading?.start();
    const userStore = useUserInfo();
    userStore
      .isReady()
      .then(() => {
        next();
      })
      .catch(() => {
        next({ name: "Login" });
      })
      .finally(() => {
        $loading?.stop();
      });
  } catch (e) {
    console.error(e);
  }
});
export { router };
